/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

(function() {

    var isCurrentlySendingMessage = false;

    var socket;
    var currentUserData;

    var displayedChatBoxesCount = 0;
    var maxChatBoxCount = 0;

    var originalTitle = $(document).attr('title');

    var flashingHeaderTimeoutId;
    var otherChatBoxCount = 0;

    var imageFileExtensions = ["JPG", "PNG", "GIF"];

    $(document).on('socketActivated', function(event) {

        if ($(".fl-chat-online-users").length === 0) {
            //  the current page does not need chat
            return;
        }

        socket = event.socket;
        currentUserData = event.currentUserData;

        var chatboxCollectionWidth = $('.fl-chatbox-collection-container').width();
        maxChatBoxCount = (chatboxCollectionWidth) / 180;
        maxChatBoxCount = Math.floor(maxChatBoxCount) + 1;

        $(".fl-chat-online-users").removeClass("display");
        initializeUIEvents();
        initializeSocketEvents();
    });

    function initializeUIEvents() {

        //  toggle online users
        $('.fl-online-users-head').click(function() {
            if ($('.fl-chat-online-users-content').is(':visible')) {
                $('.fl-chat-online-users-content, .fl-chat-online-users-content-container').hide();
            } else {
                $('.fl-chat-online-users-content, .fl-chat-online-users-content-container').show();
            }
        });

        //  toggle chatboxes
//        $('.fl-chatbox-head-contents').click(function() {
        $('.fl-chatbox-head').click(function() {
            var chatbox = $(this).closest('.fl-chatbox');
            if ($(chatbox).find('.fl-chatbox-content').is(':visible')) {
                $(chatbox).find('.fl-chatbox-content').hide();
                $(chatbox).find('.fl-chatbox-input').hide();
            } else {
                $(chatbox).find('.fl-chatbox-content').show();
                $(chatbox).find('.fl-chatbox-input').show();
            }
        });

        $('.fl-chatbox-close-button').click(function(e) {
            e.preventDefault();
            $(this).closest('.fl-chatbox').remove();
            displayedChatBoxesCount--;
            recomputeChatboxesPosition();

            otherChatbox();
        });

        //  on send chat message
        $('.fl-chatbox-input-textarea').keyup(function(event) {
            if (typeof $(this).val() === 'undefined') {
                return;
            }

            var message = $(this).val().trim();

            //  keep a reference to this since we'll lose it in the scope below
            var chatboxInputTextArea = this;

            //  if the enter key is pressed and the text area is not empty
            if (event.which === 13 && !event.shiftKey && message !== '' && !isCurrentlySendingMessage) {
                isCurrentlySendingMessage = true;
                var chatbox = $(this).closest('.fl-chatbox');
                var recipients = chatbox.attr('message-recipient-id-list').split(',');

                var messageData = {
                    recipients: recipients,
                    message: message
                };

                sendChatMessage(messageData, function(results) {

                    if (results.status == 'ERROR') {
                        alert(results.message);
                    } else {
                        //  add the sent message to this chatbox
                        var messageUI = createMessageUI(currentUserData, messageData.message, results.data.id, results.data.attachments);
                        chatbox.find('.fl-chatbox-messages-container').append(messageUI);

                        //scrollToBottom in overflow auto / default scroll bar
                        chatbox.find('.fl-chatbox-content').animate({scrollTop: chatbox.find(".fl-chatbox-messages-container").height()}, 600);

                        scrollToBottom(chatbox);
                    }
                                        
                });
                
                $(chatboxInputTextArea).val('');
                isCurrentlySendingMessage = false;
            }
        });

        $('.fl-chatbox-input-textarea').keydown(function(event) {
            var message = $(this).val().trim();
            if (event.which === 13 && message !== '') {
                event.preventDefault();
            }
        });

        $('.fl-chatbox').click(function() {
            resetNewMessageOnChatbox($(this).attr('data-id'));
        });

        //  on online user clicked
        $("body").on("click", '.fl-chat-online-users-content li, .fl-chat-online-users-content-search li', function() {
            var id = $(this).find(".fl-chat-online-user").attr('data-id');
            var displayName = $(this).find(".fl-chat-online-user").attr('data-display-name');

            openChatBoxForUser(id, displayName, $(this).find('img').attr('src'));
        });

        //  on click attach
        $('#fl-chatbox-button-attach-file').click(function() {

            //  get recipients from the chatbox where this attach button originated
            var chatbox = $(this).closest('.fl-chatbox');
            var recipients = chatbox.attr('message-recipient-id-list').split(',');

            //  create and open a dialog for sending a new message with attachments
            var dialogHtml = $('#fl-chat-ui-templates').find('.fl-dialog-attach-files-for-chat').clone(true);
            //  prevent conflicts by removing the template temporarily
            $('#fl-chat-ui-templates').find('.fl-dialog-attach-files-for-chat').html('');

            var parsedDialogHtml = dialogHtml.html().replace(/[\n\r]/g, '');
            var newDialog = new jDialog(parsedDialogHtml, "", "", "500", "", function() {
                //  return the html to the template
//                $('#fl-chat-ui-templates').find('.fl-dialog-attach-files-for-chat').html(dialogHtml.html());
            });

            $("#popup_container").on("remove", function() {
                //  return the html to the template
                $('#fl-chat-ui-templates').find('.fl-dialog-attach-files-for-chat').html(dialogHtml.html());
            });
            
            newDialog.themeDialog("modal2");

            //  manually change height of the dialog
            $('#popup_container').css('height', '500');

            $('#fl-button-send-chat-attachments').click(function() {

                var message = $('#fl-textarea-message-on-attach').val();

                if (message == '' && $('.imagePost').length == 0) {    //  TODO add && no attachments
                    alert('Type in a message or attach a file.');
                    return;
                }
                var messageData = {
                    recipients: recipients,
                    message: message
                };

                sendChatMessage(messageData, function(results) {

                    if (results.status == 'ERROR') {
                        alert(results.message);
                    } else {
                        $('#popup_cancel').click();

                        //  add the sent message to this chatbox
                        var messageUI = createMessageUI(currentUserData, messageData.message, results.data.id, results.data.attachments);
                        chatbox.find('.fl-chatbox-messages-container').append(messageUI);

                        //scrollToBottom in overflow auto / default scroll bar
                        chatbox.find('.fl-chatbox-content').animate({scrollTop: chatbox.find(".fl-chatbox-messages-container").height()}, 600);

                        //  post display operations
                        if (typeof results.data.attachments !== 'undefined') {
                            enableImageTheaterView();
                        }

                        scrollToBottom(chatbox);
                    }

                    $('.postFileLoad').addClass('display');

                });

                $(this).attr('disabled', 'disabled');
                $('.postFileLoad').removeClass('display');

            });

        });

        $(document).on('newMessageSent', function() {

            //  close all attachment dialog boxes for chat
            $('#popup_cancel').click();

        });

        window.onfocus = stopFlashingHeader;

        //search function
        $(".fl-search-online").keyup(function() {
            var search_value = $(this).val().toLowerCase();
            var displayNameOnline = "";
            var ret = "";
            var wrapEle = "";
            if (search_value !== "") {
                $(".fl-chat-online-users-content-search").show();

                $(".fl-chat-online-users-content ul li").each(function() {
                    displayNameOnline = $(this).find(".fl-online-chat-name").text().toLowerCase();
                    if (displayNameOnline.match(search_value)) {
                        wrapEle = $(this).wrap("<div />").parent();
                        wrapEle = wrapEle.html();
                        ret += wrapEle;
                        $(this).unwrap();
                    }
                });
                $(".fl-chat-online-users-content-search").find("ul").html(ret);
            } else {
                $(".fl-chat-online-users-content-search").hide();
            }
        });

        //remove search text
        $("body").click(function(e) {
            var evtarget = (window.event) ? window.event.srcElement /* for IE */ : e.target;
            if ($(evtarget).closest(".fl-search-online").length === 0) {
                $(".fl-search-online").val("");
                $(".fl-chat-online-users-content-search").hide();
            }

        });
    }

    function initializeSocketEvents() {

        socket.on('messageRecieved', function(data) {

            console.log(data);

            if ($('#fl-chatbox-' + data.id).length <= 0) {
                //  the chat box for user with id = data.id is not yet shown,
                //  display it here
                openChatBoxForUser(data.senderData.id,
                        data.senderData.displayName,
                        $(data.senderData.image).attr('src')
                        );
            }

            displayNewMessage(data.senderData, data.id, data.message, data.attachments);

            flashHeader();
            notifyNewMessageOnChatbox(data.senderData.id);
        });

    }

    function displayNewMessage(userData, messageId, message, attachments, prepend) {

        var messagesContainer = $('#fl-chatbox-' + userData.id).find('.fl-chatbox-messages-container');

        if (messagesContainer.length <= 0) {
            console.log('Missing chatbox for user: ' + userData.id);
            return;
        }

        var messageClass = '';

        if (userData.id == currentUserData.id) {
            messageClass = 'by_user';
        } else {
            messageClass = 'by_me';
        }

        var messageHTML = $('#fl-chat-ui-templates').find('.' + messageClass).clone(true);

        messageHTML.find('.userAvatar').attr('data-original-title', userData.displayName);
        messageHTML.find('.userAvatar').attr('src', $(userData.image).attr('src'));
        messageHTML.find('.messageAuthor').html(userData.displayName);
        messageHTML.find('.time').html(new Date());
        messageHTML.find('.messageText').html(message);

        if (typeof attachments !== 'undefined') {
            messageHTML.find('.messageArea').append(createMessageAttachmentsView(messageId, attachments));
        }

        if (prepend == 'prepend') {
            messagesContainer.prepend(messageHTML);
        } else {
            messagesContainer.append(messageHTML);
        }

        //  post display operations
        if (typeof attachments !== 'undefined') {
            enableImageTheaterView();
        }

        scrollToBottom('#fl-chatbox-' + userData.id);

    }

    function createMessageAttachmentsView(messageId, attachments) {

        var ret = '';

        if (attachments.extension_img.length != 0) {
            var w = "";
            var h = "";
            // Image
            if (attachments.extension_img.length != 0) {
                var folderName = attachments.postFolderName;
                var listImg = attachments.img;
                // Image Class
                var imageView = "imageView openImageView";
                //width
                if (attachments.image_resize[0] > 600) {
                    w = "500";
                } else {
                    w = attachments.image_resize[0];
                }
                // Height
                if (attachments.image_resize[1] > 600) {
                    h = "500";
                } else {
                    h = attachments.image_resize[1];
                }
                for (var a in listImg) {
                    var listImg_extension = listImg[a].split(".");
                    var extension = listImg_extension[listImg_extension.length - 1];

                    if (typeof extension !== 'undefined') {
                        extension = extension.toUpperCase();
                    }

                    if (imageFileExtensions.indexOf(extension) != -1) {

                        if (attachments.lengthImg == "1") {
                            ret += '<center>';
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[a] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[a] + '"  width="' + w + '" height="' + h + '">';
                            ret += '</center>';
                        } else if (attachments.lengthImg == "2") {
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[a] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[a] + '"  style="width:40%;">';
                        } else if (attachments.lengthImg == "3") {
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[a] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[a] + '"  style="width:30%;">';
                        } else if (attachments.lengthImg > 4) {
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[a] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[a] + '"  style="width:30%;">';
                        } else if (attachments.lengthImg == "4") {
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[0] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[0] + '"  style="width:30%;">';
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[1] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[1] + '"  style="width:30%;">';
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[2] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[2] + '"  style="width:30%;">';
                            ret += '<img src="/images/messageUpload/' + folderName + '/' + listImg[3] + '" class="avatar ' + imageView + ' fl-image-theater group_1_' + messageId + '"  href="/images/messageUpload/' + folderName + '/' + listImg[3] + '"    width="' + w + '" height="' + h + '">';

                            break;
                        }

                    }
                }
            }

        }
        if (attachments.extension_file.length != 0) {
            // Files
            if (attachments.extension_file.length != 0) {
                var folderName = attachments.postFolderName;
                var listImg = attachments.img;

                for (var a in listImg) {
                    var listImg_extension = listImg[a].split(".");
                    var extension = listImg_extension[listImg_extension.length - 1];

                    if (typeof extension !== 'undefined') {
                        extension = extension.toUpperCase();
                    }

                    if (imageFileExtensions.indexOf(extension) == -1) {
                        ret += '<form method="POST" style="text-decoration: underline;">';
                        ret += '<input type="submit" class="cursor tip" data-original-title="' + listImg[a] + '" style="opacity: 0;position: absolute;width: 100%;">';
                        ret += '<a class="cursor apps">';
                        var num = "1";
                        ret += num++ + ") " + listImg[a];
                        ret += '</a>';
                        ret += '</input>';
                        ret += '<input type="hidden" value="' + listImg[a] + '" name="attachment_filename">';
                        ret += '<input type="hidden" value="images/messageUpload/' + folderName + '/' + listImg[a] + '" name="attachment_location">';
                        ret += '</form>';
                    }
                }
            }
        }

        return ret;

    }

    function enableImageTheaterView() {
        $('.fl-image-theater').colorbox({rel: '.fl-image-theater', width: "75%", height: "80%"});
    }

    function scrollToBottom(chatboxId) {

        var chatbox = $(chatboxId);
//        var chatboxContent = chatbox.find('.fl-chatbox-content');
        var chatboxContent = chatbox.find('.fl-chatbox-messages-container');

        chatboxContent.perfectScrollbar('destroy');
        chatboxContent.perfectScrollbar({
            wheelSpeed: 20
        });
        chatboxContent.scrollTop(chatboxContent.prop('scrollHeight'));
        chatboxContent.perfectScrollbar('update');

    }

    function flashHeader() {

        //  remove previous flashing header timeout id
        if (flashingHeaderTimeoutId != null) {
            stopFlashingHeader();
        }

        var isOriginal = true;
        flashingHeaderTimeoutId = setInterval(function() {

            if (isOriginal) {
                $(document).attr('title', 'new message');
            } else {
                $(document).attr('title', originalTitle);
            }

            isOriginal = !isOriginal;
        }, 1600);

    }

    function notifyNewMessageOnChatbox(id) {

        var chatbox = $('#fl-chatbox-' + id);
        var newMessageCount = parseInt(chatbox.find('.fl-new-chat-message-counter').html());

        if (newMessageCount == 'NaN') {
            newMessageCount = 0;
        }

        newMessageCount++;

        chatbox.find('.fl-new-chat-message-counter').html(newMessageCount);
        chatbox.find('.fl-new-chat-message-counter').css('display', 'block');
        //chatbox.find('.fl-online-chat-user-image').css('display', 'none');

        chatbox.find('.fl-new-chat-message-counter').effect('shake', {
            direction: 'up',
            distance: 10
        });

    }

    function resetNewMessageOnChatbox(id) {

        var chatbox = $('#fl-chatbox-' + id);
        var newMessageCount = parseInt(chatbox.find('.fl-new-chat-message-counter').html());

        if (newMessageCount == 'NaN' || newMessageCount == 0) {
            return;
        }

        chatbox.find('.fl-new-chat-message-counter').html(0);
        chatbox.find('.fl-new-chat-message-counter').css('display', 'none');
        chatbox.find('.fl-online-chat-user-image').css('display', 'block');

        stopFlashingHeader();

    }

    function stopFlashingHeader() {
        if (flashingHeaderTimeoutId != null) {
            clearInterval(flashingHeaderTimeoutId);
            flashingHeaderTimeoutId = null;
        }

        $(document).attr('title', originalTitle);
    }

    function createLoadingUI() {
        var loadingUI = $('#fl-chat-ui-templates').find('.fl-loading-list-item').clone();
        return loadingUI;
    }

    function createMessageUI(userData, message, messageId, attachments) {

        var messageClass = '';

        if (userData.id == currentUserData.id) {
            messageClass = 'by_user';
        } else {
            messageClass = 'by_me';
        }

        var messageHTML = $('#fl-chat-ui-templates').find('.' + messageClass).clone(true);

        messageHTML.find('.userAvatar').attr('data-original-title', userData.displayName);
        messageHTML.find('.userAvatar').attr('src', $(userData.image).attr('src'));
        messageHTML.find('.messageAuthor').html(userData.displayName);
        messageHTML.find('.time').html(new Date());
        messageHTML.find('.messageText').html(message);

        if (typeof attachments !== 'undefined') {
            messageHTML.find('.messageArea').append(createMessageAttachmentsView(messageId, attachments));
        }

        //  post display operations
        if (typeof attachments !== 'undefined') {
            enableImageTheaterView();
        }

        return messageHTML;
    }

    function openChatBoxForUser(userId, userDisplayName, userImageURL) {

        var chatbox;
        var senderData = [];
        var currentUserDataID = currentUserData.id;
        if ($('#fl-chatbox-' + userId).length == 0 && $('#fl-chatbox-reserve-' + userId).length == 0) {
            //  add a new chatbox to the container
            chatbox = createNewChatbox(userId, userDisplayName, userImageURL);
            var chatboxContent = chatbox.find('.fl-chatbox-messages-container');


            if (computeChatboxNextRightPosition() == 0) {
                chatbox.css('right', 1330);
            } else {
                chatbox.css('right', computeChatboxNextRightPosition());

            }
            $.post("/ajax/message", {
                action: "readMsg",
                fetch_limit: 15,
                recipients: userId + "," + currentUserDataID,
                order: 'DESC'
            }, function(data) {
                data = JSON.parse(data);
                var dataMessage = data[0]['replyMsg'];

                otherChatbox();

                //  clear chatbox messages first before adding the messages
                chatbox.find('.fl-chatbox-messages-container').html('');
                for (var i in dataMessage) {
                    senderData = {
                        id: dataMessage[i]['senderID'],
                        displayName: dataMessage[i]['sendBy'],
                        image: dataMessage[i]['images']
                    };
                    if (dataMessage[i]['senderID'] == currentUserDataID) {
                        var messageUI = createMessageUI(currentUserData,
                                dataMessage[i]['message'],
                                dataMessage[i]['id'],
                                dataMessage[i]['message_attachment']
                                );
                        chatbox.find('.fl-chatbox-messages-container').prepend(messageUI);
                    } else {
                        displayNewMessage(senderData,
                                dataMessage[i]['id'],
                                dataMessage[i]['message'],
                                dataMessage[i]['message_attachment'],
                                'prepend'
                                );
                    }
                }
                scrollToBottom(chatbox);
            });

            chatbox.addClass("appendedChatBox");
            $('.fl-chatbox-collection-container').append(chatbox);

            displayedChatBoxesCount++;

            chatboxContent.append(createLoadingUI());
            chatboxContent.height(chatbox.find('.fl-chatbox-content').height());
            chatboxContent.perfectScrollbar('update');
            chatbox.find(".fl-chatbox-input-textarea").focus();
        } else {
            chatbox = $('#fl-chatbox-' + userId);
        }

    }

    function createNewChatbox(userId, userDisplayName, userImageURL) {

        var chatbox = $('#fl-chat-ui-templates').find('.fl-chatbox').clone(true);

        chatbox.attr('id', 'fl-chatbox-' + userId);
        chatbox.attr('data-id', userId);
        chatbox.attr('message-recipient-id-list', userId);
        chatbox.find('.fl-online-chat-name').html(userDisplayName);
        chatbox.find('.fl-online-chat-user-image').attr('src', userImageURL);

        //  setup perfect scrollbar for the chatbox contents
//        var chatboxContent = chatbox.find('.fl-chatbox-content');
        var chatboxContent = chatbox.find('.fl-chatbox-messages-container');
        chatboxContent.perfectScrollbar({
            wheelSpeed: 20,
            wheelPropagation: false,
            minScrollbarLength: 20
        });

        return chatbox;

    }

    function computeChatboxNextRightPosition() {

        var right = 0;

        if (displayedChatBoxesCount < maxChatBoxCount) {
            right = (displayedChatBoxesCount * 270) + 250;
        }

        return right;

    }

    function recomputeChatboxesPosition() {

        //  no need to adjust if no chatboxes are displayed
        if (displayedChatBoxesCount == 0) {
            return;
        }

        displayedChatBoxesCount = 0;

        $('.fl-chatbox').each(function() {

            if (displayedChatBoxesCount < maxChatBoxCount) {
                $(this).css('right', computeChatboxNextRightPosition());

                displayedChatBoxesCount++;
            } else {

            }

        });

        displayedChatBoxesCount--;

    }

    function sendChatMessage(messageData, onDone) {
        if (!messageData) {
            //  message data missing, cannot continue message push
            return;
        }

        var message = messageData.message;
        var sendTo = messageData.recipients;
        var data = messageData;

        var messageDataForSaving;

        var attachmentsFormatted = {};
        $('.imagePost').each(function(eqindex) {
            attachmentsFormatted['name_' + eqindex] = $(this).attr("data-name");
        });

        var attachmentsString = JSON.stringify(attachmentsFormatted);

        //  setup data for saving new message
        messageDataForSaving = {
            action: 'newMsg',
            title: message,
            msg: message,
            userListID: sendTo.join(','),
            imagesGet: attachmentsString,
            folder_location: 'messageUpload'
        };

        $.post("/ajax/message", messageDataForSaving, function(response) {

            if (response.newMessageId) {

                //  message was successfully saved to server, socket may now notify
                //  the message recipients

                console.log(response);

                //  remove the id of the sender from the sendTo variable if it is\
                //  existing there
                var ownIdIndex = sendTo.indexOf(currentUserData.id);
                if (ownIdIndex > -1) {
                    sendTo.splice(ownIdIndex, 1);
                }

                data.id = response.newMessageId;
                data.senderData = currentUserData;
                data.sendTo = sendTo;
                data.message = messageData.message;
                data.msg = messageData.message;

                data.senderData = currentUserData;

                data.attachments = response.attachments;

                socket.emit('message', data);

                if (typeof onDone !== 'undefined') {
                    onDone({
                        status: 'SUCCESS',
                        data: data,
                        message: 'Message saved and sent to recipients'
                    });
                }
            } else {
                console.log('Failed to save message to server');

                if (typeof onDone !== 'undefined') {
                    onDone({
                        status: 'ERROR',
                        message: 'Failed to save message to server'
                    });
                }
            }
        });
    }

    function otherChatbox() {
        var lastChatBox;
        var reserveChatBoxHTML = $('.reserve-chat-box-list').first().clone(true);
        var data_id;

        $(".fl-chatbox").each(function() {
            //assign variable
            lastChatBox = $(this);
            data_id = lastChatBox.attr("data-id");


            //filtering the appended chatbox only
            if (lastChatBox.hasClass("appendedChatBox")) {

                if (lastChatBox.offset().left <= 300 && lastChatBox.offset().left >= 200) {
                    //assign other chatbox left
                    $(".other-chatbox").css("left", lastChatBox.offset().left - 30);
                }
                if (lastChatBox.offset().left < 200) {
                    //show the other chatbox link
                    $(".other-chatbox").show();

                    //other chatbox count
                    if ($("#fl-chatbox-reserve-" + data_id).length == 0) {
                        reserveChatBoxHTML.attr({
                            "id": "fl-chatbox-reserve-" + data_id,
                            "data-id": data_id,
                            "displayName": lastChatBox.find(".fl-online-chat-name").text(),
                            "img": lastChatBox.find(".fl-online-chat-user-image").attr("src")
                        });
                        reserveChatBoxHTML.addClass("appended-reserve-chat-box");
                        $(".reserve-chat-box").append(reserveChatBoxHTML);
                        otherChatBoxCount++;
                    }
                    //remove the excess chatbox to fit in the window
                    lastChatBox.remove();
                    displayedChatBoxesCount--;
                } else {
                    //hide the other chatbox link
                    if (otherChatBoxCount == 1) {
                        $(".other-chatbox").hide();
                    }
                }
                $(".other-chatbox").text(otherChatBoxCount);
            }
        });
        countAvailableSlot();
        var chatbox;
        var id;
        var displayName;
        var img;

        $(".appended-reserve-chat-box").each(function(equi) {
            if (equi < countAvailableSlot()) {
                id = $(this).attr("data-id");
                displayName = $(this).attr("displayName");
                img = $(this).attr("img");

                chatbox = createNewChatbox(id, displayName, img);
                if (computeChatboxNextRightPosition() == 0) {
                    chatbox.css('right', 1330);
                } else {
                    chatbox.css('right', computeChatboxNextRightPosition());

                }
                var chatboxContent = chatbox.find('.fl-chatbox-messages-container');
                chatbox.addClass("appendedChatBox");
                $('.fl-chatbox-collection-container').append(chatbox);
                displayedChatBoxesCount++;
                chatboxContent.height(chatbox.find('.fl-chatbox-content').height());
                chatboxContent.perfectScrollbar('update');

                $(this).remove();
                otherChatBoxCount--;
                $(".other-chatbox").text(otherChatBoxCount);
            }
        });
        // console.log()
        // openChatBoxForUser(id, displayName, $(this).find('img').attr('src'));   

    }

    function countAvailableSlot() {
        var windowWidth = $(window).width();
        var windowChatBoxWidth = (displayedChatBoxesCount * 270) + 250;
        var diffChatWindow = windowWidth - windowChatBoxWidth;
        return Math.round(diffChatWindow / 270) - 1;
    }
    $(window).resize(function() {
        otherChatbox();
    });
}());


//position of chatbox in all workspace
$(document).ready(function() {

    if ($('.fl-form-properties-wrapper').length > 0) {
        var eleLocation = $('.fl-form-properties-wrapper');
        var eleChatOnlineUser = $('.fl-chat-online-users');
        var flChatbox = $('.fl-chatbox').parent();
        $(eleChatOnlineUser).appendTo(eleLocation);
        $(flChatbox).appendTo(eleLocation);

        eleChatOnlineUser.css({
            "position": "absolute",
            "right": 300,
            "bottom": 15

        });
    }
    ;

});